package netstack

import (
    "go-os-qemu/pkg/nic"
    "go-os-qemu/pkg/vga"
)

// High-level HTTP GET: connect to dstIP:dstPort and request path
func HTTPGet(e *nic.E1000, dstIP [4]byte, dstPort uint16, path string) bool {
    c := TCPConnect(e, dstIP, dstPort)
    if c == nil { return false }
    // wait for establishment
    for i := 0; i < 200; i++ {
        e.DumpRx(8)
        if c.state == TCP_ESTABLISHED { break }
    }
    if c.state != TCP_ESTABLISHED {
        vga.SetColor(vga.ColorYellow, vga.ColorBlack)
        vga.Println("HTTP: connection not established (timeout)")
        vga.SetColor(vga.ColorLightGray, vga.ColorBlack)
        return false
    }
    // Build minimal HTTP/1.0 GET request
    var req [256]byte
    off := 0
    // "GET "
    req[off+0] = 'G'; req[off+1] = 'E'; req[off+2] = 'T'; req[off+3] = ' '; off += 4
    // path
    for i := 0; i < len(path) && off < len(req)-16; i++ { req[off] = path[i]; off++ }
    // " HTTP/1.0\r\n\r\n"
    tail := " HTTP/1.0\r\n\r\n"
    for i := 0; i < len(tail) && off < len(req); i++ { req[off] = tail[i]; off++ }
    // use send queue and分片发送
    payload := req[:off]
    tcpQueue(c, payload)
    tcpTrySend(e, c)
    ok := true
    if ok {
        vga.SetColor(vga.ColorLightGray, vga.ColorBlack)
        vga.Print("HTTP GET sent to "); printIP(dstIP); vga.Print(":"); printDec(int(dstPort)); vga.Print(" path ");
        for i := 0; i < len(path); i++ { vga.Print(string(path[i])) }
        vga.Println("")
    }
    // poll a bit to receive response (printing handled in TCP receive)
    for i := 0; i < 300; i++ { e.DumpRx(8) }
    return ok
}